<template>
  <div class="app">
    <div class="box">
      <a-card class="v-card">
        <template #title>
          <HeartTwoTone twoToneColor="#eb2f96" />
          管理员登录
        </template>
        <!-- 表单 -->
        <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 17 }">
          <a-form-item label="用户名" v-bind="validateInfos.username">
            <a-input v-model:value="modelRef.username" />
          </a-form-item>
          <a-form-item label="密码" v-bind="validateInfos.password">
            <a-input-password v-model:value="modelRef.password" />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click.prevent="onSubmit">提交</a-button>
            <a-button style="margin-left: 10px" @click="reset">重置</a-button>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script>
import { HeartTwoTone } from "@ant-design/icons-vue";
import { reactive } from "vue";
import { Form, message } from "ant-design-vue";
import { reqLogin } from "../../api";
import { saveUser } from "../../utils";
import { useRouter } from "vue-router";
const useForm = Form.useForm;

function useAdminForm() {
  const modelRef = reactive({
    username: "",
    password: "",
  });

  const router = useRouter();

  const { resetFields, validate, validateInfos } = useForm(
    modelRef,
    reactive({
      username: [
        {
          required: true,
          message: "请输入用户名",
        },
      ],
      password: [
        {
          required: true,
          message: "请输入密码",
        },
      ],
    })
  );

  const onSubmit = () => {
    validate()
      .then(async (result) => {
        const { success, data } = await reqLogin(result);
        if (success) {
          message.success("登陆成功");
          saveUser(data.admin);
          router.replace('/admin')
        } else {
          message.error("登陆失败，用户名或密码错误");
        }
      })
      .catch((err) => {
        console.log("error", err);
      });
  };

  const reset = () => {
    resetFields();
  };

  return {
    validateInfos,
    reset,
    modelRef,
    onSubmit,
  };
}

export default {
  name: "Login",
  components: {
    HeartTwoTone,
  },
  setup() {
    return {
      ...useAdminForm(),
    };
  },
};
</script>

<style>
#app {
  width: 100%;
  height: 100%;
}

.app {
  position: relative;
  width: 100%;
  height: 100%;
  background: url("../../assert/images/6.jpg") no-repeat center;
}

.box {
  width: 400px;
  height: 300px;
  position: absolute;
  top: 20%;
  right: 20%;
}

.v-card {
  width: 100%;
  height: 100%;
}
</style>